import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Solution1().lengthOfLIS(new int[]{10,9,2,5,3,7,101,18}));
        System.out.println(new Solution1().lengthOfLIS(new int[]{0,1,0,3,2,3}));
        System.out.println(new Solution1().lengthOfLIS(new int[]{7,7,7,7,7,7,7}));
    }
}


class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = 1;
        int longest = 1;
        for (int i = 1; i < nums.length; i++) {
            dp[i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[j] + 1, dp[i]);
                }
            }
            longest = Math.max(longest, dp[i]);
        }
        return longest;
    }
}

//贪心 + 二分查找 O(nlogn)
class Solution1 {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length + 1];        //dp[i]为长度为i的子序列的末尾元素最小值
        dp[1] = nums[0];
        int maxLen = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > dp[maxLen]) {
                maxLen++;
                dp[maxLen] = nums[i];
            }
            int largest = findLargest(dp, maxLen, nums[i]);
            if (dp[largest + 1] > nums[i]) {
                dp[largest + 1] = nums[i];
            }
        }
        return maxLen;
    }

    int findLargest(int[] dp, int maxLen, int v) {
        int l = 1, r = maxLen;
        while (l <= r) {
            int mid = (l + r) / 2;
            if (dp[mid] >= v) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return r;
    }
}